/*
 * Copyright (C) 2015 truth
 *
 * This program is non-free software, but you can redistribute it and/or modify
 * it if you are in org.hejianjiao(Huangshi Hejianjiao) team.
 */
package com.truthbean.jutils.security;

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.crypto.BadPaddingException;

import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;


/**
 * 
 * @ClassName: Security
 * @Description: 安全相关的判断类，如密码的安全性
 * @Author truth
 * @Since 2015年2月20日 下午8:05:51
 *
 */
public class Security {
	/**
	 * 
     * @param str
     * @return 
	 * @Title: isSecurityPassword
	 * @Description: 密码判断是否为自定的安全规格 如，是否包含数字、大小写字符、特殊字符，长度是否大于8
	 * @Author: truth
	 * @Since: 2015年2月20日 下午8:06:32
	 * @Params: @param str
	 * @Params: @return
	 * @Return: boolean
	 * @Throws:
	 */
	public static boolean isSecurityPassword(String str) {
		String regEx1 = ".*?[^a-zA-Z\\d]+.*?";
		String regEx2 = ".*?[a-z]+.*?";
		String regEx3 = ".*?[A-Z]+.*?";
		String regEx4 = ".*?[\\d]+.*?";
		Pattern pat1 = Pattern.compile(regEx1);
		Matcher matcher1 = pat1.matcher(str);
		Pattern pat2 = Pattern.compile(regEx2);
		Matcher matcher2 = pat2.matcher(str);
		Pattern pat3 = Pattern.compile(regEx3);
		Matcher matcher3 = pat3.matcher(str);
		Pattern pat4 = Pattern.compile(regEx4);
		Matcher matcher4 = pat4.matcher(str);
		return matcher1.find() && matcher2.find() && matcher3.find()
				&& matcher4.find() && str.length() >= 8;
	}

	/**
	 * 定义字符集
	 * @param
	 * @return
	 */
	private static final char[] CHARS = { '0', '1', '2', '3', '4', '5', '6', '7',
			'8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
			'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
			'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
			'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
			'Y', 'Z', '~', '`', '!', '@', '#', '$', '%', '^', '&', '*', '(',
			')', '_', '-', '+', '=', '[', ']', '{', '}', '|', '\\', ';', ':',
			'"', '\'', ',', '<', '.', '>', '?', '/'};

	/**
	 * @param passLength 随机密码长度
	 * @return 随机密码数组
	 */
	public static String getPasswords(int passLength) {
		String passwords = "";// 新建一个长度为指定需要密码个数的字符串数组
		SecureRandom random = new SecureRandom();
		//Random random = new Random();
		StringBuilder password = new StringBuilder("");// 保存生成密码的变量
		for (int m = 1; m <= passLength; m++) {// 内循环 从1开始到密码长度 正式开始生成密码
			password.append(CHARS[random.nextInt(CHARS.length)]);// 为密码变量随机增加上面字符中的一个
		}
		passwords = password.toString();// 将生成出来的密码赋值给密码数组
		if(Security.isSecurityPassword(passwords))
			return passwords;
		else
			return getPasswords(passLength);
	}
	
	/**
	 * 将字节数组转换为十六进制字符串
	 * @param src 字节数组
	 * @return
	 */
	public static String bytesToHexString(byte[] src) {
		StringBuilder stringBuilder = new StringBuilder("");
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = 0; i < src.length; i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString();
	}
	
	/**
	 * 将十六进制字符串转换为字节数组
	 * 
	 * @param hexString
	 *            十六进制字符串
	 * @return
	 */
	public static byte[] hexStringToBytes(String hexString) {
		if (hexString == null || hexString.equals("")) {
			return null;
		}
		hexString = hexString.toUpperCase();
		int length = hexString.length() / 2;
		char[] hexChars = hexString.toCharArray();
		byte[] d = new byte[length];
		for (int i = 0; i < length; i++) {
			int pos = i * 2;
			d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
		}
		return d;
	}
	
	private static byte charToByte(char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}
	
	
}
